import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { OrganizationService } from 'src/app/services/organization.service';
import { ExceptionHandler } from 'src/app/handler/exception.handler';
import { PersonnelService } from 'src/app/services/personnel.service';
import { NzMessageService } from 'ng-zorro-antd/message';

@Component({
    selector: 'zepride-super-authority',
    templateUrl: './super-authority.component.html',
    styleUrls: ['./super-authority.component.less']
})
export class SuperAuthorityComponent implements OnInit {

    checkedAll = false;
    checkedsuperhistory = false;
    checkedsuperall = false;
    total: number;
    totalchecked: number;
    indeterminate = false;
    listOfCurrentPageData = [];
    listOfData = [];
    setOfCheckedId = new Set<number>();
    validateForm: FormGroup;
    isVisibleAdd = false;
    isVisibleEdit = false;
    departlist = [];
    departPersonlist: any;
    userDetails: any;
    superDetails: any;
    isSpinning = false;
    pageIndex = 1;
    pageSize = 10;

    constructor(
        private fb: FormBuilder,
        private organizationService: OrganizationService,
        private personnelService: PersonnelService,
        private message: NzMessageService
    ) { }

    ngOnInit(): void {
        this.getdepartlist();
        this.getSuperlist();
        this.buildForm();
        this.subscribeValueChanges();
    }

    updateCheckedSet(id: number, checked: boolean): void {
        if (checked) {
            this.setOfCheckedId.add(id);
            this.totalchecked = [... this.setOfCheckedId].length;
        } else {
            this.setOfCheckedId.delete(id);
            this.totalchecked = [... this.setOfCheckedId].length;
        }
    }

    onItemChecked(id: number, checked: boolean) {
        this.updateCheckedSet(id, checked);
        this.refreshCheckedStatus();
    }

    onAllChecked(value: boolean) {
        this.listOfCurrentPageData.forEach(item => this.updateCheckedSet(item.id, value));
        this.refreshCheckedStatus();
    }

    onCurrentPageDataChange($event): void {
        this.listOfCurrentPageData = $event;
        this.refreshCheckedStatus();
    }

    refreshCheckedStatus(): void {
        let isCheckAll = false;
        let isIndeterminate = false;
        if (this.listOfCurrentPageData && this.listOfCurrentPageData.length) {
            isCheckAll = this.listOfCurrentPageData.every(item => this.setOfCheckedId.has(item.id));
            isIndeterminate = this.listOfCurrentPageData.some(item => this.setOfCheckedId.has(item.id)) && !this.checkedAll;
        }
        this.checkedAll = isCheckAll;
        this.indeterminate = isIndeterminate;
    }

    // 展示添加对话框
    showAdd() {
        this.isVisibleAdd = true;
    }

    subscribeValueChanges() {
        this.validateForm.controls.department.valueChanges.subscribe(() => {
            this.getdepartPersonlist();
        });
        this.validateForm.controls.person.valueChanges.subscribe(() => {
            this.getdepartPersonDetails();
        });
    }

    async handleOkAdd() {
        this.submitForm();
        if (this.validateForm.valid) {
            await this.addSuperPerson();
            this.validateForm.reset();
            this.isVisibleAdd = false;
        }
    }

    handleCancel() {
        this.validateForm.reset();
        this.isVisibleAdd = false;
        this.isVisibleEdit = false;

    }
    // 展示修改对话框
    showEdit(data) {
        this.isVisibleEdit = true;
        this.superDetails = data;
        this.checkedsuperhistory = data.superPermits.some(item => item.permitName == '历史数据修改');
        this.checkedsuperall = data.superPermits.some(item => item.permitName == '所有数据查看');
    }

    // 修改权限
    async handleOkEdit() {
        this.superDetails.superPermits = [
            {
                refObjectId: '351763d250384d5380d815b343aede01',
                refObjectType: 'admin',
                permitId: '历史数据修改',
                permitName: '历史数据修改'
            },
            {
                refObjectId: '7175cd7eaa214bc6930522bd8d1cc51e',
                refObjectType: 'admin',
                permitId: '所有数据查看',
                permitName: '所有数据查看'
            }
        ];
        if (!this.checkedsuperhistory) {
            this.superDetails.superPermits = this.superDetails.superPermits.filter(item => item.permitName != '历史数据修改');
        }
        if (!this.checkedsuperall) {
            this.superDetails.superPermits = this.superDetails.superPermits.filter(item => item.permitName != '所有数据查看');
        }

        await this.personnelService.setSuper(this.superDetails);
        this.message.success('超级权限修改成功');
        await this.getSuperlist();
        this.isVisibleEdit = false;

    }
    submitForm() {
        // tslint:disable-next-line: forin
        for (const i in this.validateForm.controls) {
            this.validateForm.controls[i].markAsDirty();
            this.validateForm.controls[i].updateValueAndValidity();
        }
    }
    buildForm() {
        this.validateForm = this.fb.group({
            department: [null, [Validators.required]],
            person: [null, [Validators.required]],
            jurisdiction: [null, [Validators.required]],
        });
    }
    // 获取部门列表
    async getdepartlist() {
        try {
            const params = {
                organizationId: this.organizationService.orgid,
                objectName: 'Department'
            };
            const data = await this.organizationService.getOrganizationTrees(params);
            this.departlist = data ? data : [];


        } catch (error) {
            ExceptionHandler.current.handleError(error);
        }
    }

    // 获取部门下面人员
    async getdepartPersonlist() {
        try {
            if (!this.validateForm.controls.department.value) { return; }
            const params = {
                parentId: this.validateForm.controls.department.value
            };
            const { list } = await this.personnelService.queryUsers(params);
            this.departPersonlist = list ? list : [];
        } catch (error) {
            ExceptionHandler.current.handleError(error);
        }
    }

    // 获取人员详情
    async getdepartPersonDetails() {
        try {
            if (!this.validateForm.controls.person.value) { return; }
            const id = this.validateForm.controls.person.value;
            const userDetails = await this.personnelService.getUserInfoById(id);
            this.userDetails = userDetails;
        } catch (error) {
            ExceptionHandler.current.handleError(error);
        }
    }
    // 新增添加超级权限
    async addSuperPerson() {
        try {
            if (!this.userDetails.acc || !this.userDetails.acc.superPermits) {
                let superPermits = [];
                superPermits = this.validateForm.controls.jurisdiction.value.map(item => {
                    if (item == 'history') {
                        return {
                            refObjectId: '351763d250384d5380d815b343aede01',
                            refObjectType: 'admin',
                            permitId: '历史数据修改',
                            permitName: '历史数据修改'
                        };
                    } else if (item == 'all') {
                        return {
                            refObjectId: '7175cd7eaa214bc6930522bd8d1cc51e',
                            refObjectType: 'admin',
                            permitId: '所有数据查看',
                            permitName: '所有数据查看'
                        };
                    }
                });
                this.userDetails.acc = { ...this.userDetails.acc, superPermits };
            }
            await this.personnelService.setSuper(this.userDetails.acc);
            this.message.success('新增超级权限成功');
            this.getSuperlist();
        } catch (error) {
            ExceptionHandler.current.handleError(error);
        }
    }

    // 获取超级权限人员列表
    async getSuperlist() {
        this.isSpinning = true;
        try {
            const { list, total } = await this.personnelService.getSuperPersonlist();
            this.listOfData = list ? list : [];
            this.total = total;
            console.log(this.listOfData);
            this.isSpinning = false;
        } catch (error) {
            ExceptionHandler.current.handleError(error);
            this.isSpinning = false;

        }
    }

    // 删除超级权限人员
    async delSuperPerson() {

        for (const item of this.listOfData) {
            if (this.setOfCheckedId.has(item.id)) {
                item.acc.superPermits = null;
                await this.personnelService.setSuper(item.acc);
            }
        }

        this.setOfCheckedId.clear();

        await this.getSuperlist();
        this.message.success('删除成功');
    }

}
